<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox, ElLoading } from 'element-plus'

import { Table } from '@/components/Table'
import {
  adminCsGoodsAddApi,
  // adminCsGoodsBatchDelApi,
  adminCsGoodsDelApi,
  adminCsGoodsEditApi,
  adminCsGoodsListApi
} from '@/api/cs/goods'
import { adminShopShopListeApi } from '@/api/cs/shop'
import { ucUserListAdminApi } from '@/api/uc/user'
import { adminCsClassListApi } from '@/api/cs/class'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/cs/goods/types'
import { ref, unref, reactive } from 'vue'
import Add from './components/Add.vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
// import Sku from './components/Sku.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

import { getDictLabel } from '@/utils/lee'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

const iconEdit = useIcon({ icon: 'ep:edit' })
// const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  any
>({
  getListApi: adminCsGoodsListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
// 所属分类
const newClassData = ref<any[]>([])
const getClassList = async () => {
  // const loadingInstance = ElLoading.service(options)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await adminCsClassListApi({})
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    newClassData.value = [{ class_id: '0', class_name: ' ' }, ...res.data]
  }
}
getClassList()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'goods_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'goods_name',
    label: '商品名称',
    search: {
      show: true
    }
  },
  {
    field: 'goods_sn',
    label: '商品编号',
    search: {
      show: true
    }
  },
  {
    field: 'shop_id',
    label: '所属店铺',
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: adminShopShopListeApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择店铺（双击选择）',
        nameField: 'shop_name',
        valueField: 'shop_id',
        crudSchemas: [
          {
            field: 'shop_name',
            label: '店铺名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: adminShopShopListeApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择店铺（双击选择）',
        nameField: 'shop_name',
        valueField: 'shop_id',
        crudSchemas: [
          {
            field: 'shop_name',
            label: '店铺名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'shop_name',
    label: '所属店铺',
    form: {
      show: false
    }
  },
  {
    field: 'user_id',
    label: '创建人',
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucUserListAdminApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择创建人（双击选择）',
        nameField: 'user_name',
        relNameField: 'nickname',
        valueField: 'user_id',
        crudSchemas: [
          {
            field: 'nickname',
            label: '姓名',
            search: {
              show: true
            }
          },
          {
            field: 'username',
            label: '用户名',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'user_name',
    label: '创建人',
    form: {
      show: false
    }
  },
  {
    field: 'class_id',
    label: '所属分类',
    search: {
      component: 'TreeSelect',
      componentProps: {
        data: newClassData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        data: newClassData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },

  {
    field: 'class_name',
    label: '所属分类',
    form: {
      show: false
    }
  },
  {
    field: 'goods_price',
    label: '商品价格',
    form: {
      component: 'InputNumber',
      componentProps: {
        precision: 2,
        step: 0.01,
        mix: 0
      },
      show: true
    }
  },
  {
    field: 'is_up_shelf',
    label: '是否上架',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != null ? getDictLabel(dict, 'is', cellValue) : getDictLabel(dict, 'is', 0)
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.is
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.is
      },
      show: true
    }
  },
  {
    field: 'goods_thumbnail',
    label: '缩略图URL',
    table: {
      show: false
    },
    form: {
      component: 'Upload'
    },
    detail: {
      span: 24,
      show: true
    }
  },
  // {
  //   field: 'sku_list',
  //   label: '规格列表',
  //   table: {
  //     show: false
  //   },
  //   form: {
  //     componentProps: {
  //       type: 'textarea'
  //     },
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     show: true
  //   }
  // },
  {
    field: 'goods_describe',
    label: '商品描述',
    form: {
      componentProps: {
        type: 'textarea'
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },

  {
    field: 'action',
    width: 300,
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

// const delLoading = ref(false)

// const delData = async () => {
//   const { getSelections } = methods
//   const selections = await getSelections()
//   const ids = selections.map((v) => v.goods_id)
//   delLoading.value = true
//   ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
//     confirmButtonText: t('common.delOk'),
//     cancelButtonText: t('common.delCancel'),
//     type: 'warning'
//   })
//     .then(async () => {
//       let res = await adminCsGoodsBatchDelApi({ ids: ids.join(',') })
//         .catch(() => {})
//         .finally(() => {
//           delLoading.value = false
//         })
//       if (res) {
//         getList()
//       }
//     })
//     .catch(() => {})
// }

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.goods_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (goods_id) => {
  let delRes = await adminCsGoodsDelApi({ goods_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

// const seeEdit = async () => {
//   const edit = unref(editRef)
//   await edit?.elFormRef?.validate(async (isValid) => {
//     if (isValid) {
//       const data: any = await edit?.getFormData()
//       console.log('getFormData', data)
//     }
//   })
// }

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data: any = await edit?.getFormData()
          loading.value = false
          let res = await adminCsGoodsEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await adminCsGoodsAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <!-- <Sku /> -->
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <!-- <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton> -->
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" :icon="iconEdit" @click="action('edit', row)" title="编辑">
          编辑
        </ElButton>
        <!-- <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="详情">
          详情
        </ElButton> -->
        <ElButton type="danger" :icon="iconDel" @click="action('del', row)" title="删除">
          删除
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <!-- <ElButton :loading="loading" @click="seeEdit()"> 查看保存值 </ElButton> -->
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
